/*
 * @Author: szx
 * @Date: 2022-05-06 15:41:58
 * @LastEditTime: 2022-05-06 16:02:53
 * @Description:
 * @FilePath: \leetcode\剑指offerII\113\113.js
 */
/**
 * @param {number} numCourses
 * @param {number[][]} prerequisites
 * @return {number[]}
 */
var findOrder = function (numCourses, prerequisites) {
    const edges = new Array(numCourses).fill(0).map(() => []),
        indeg = new Array(numCourses).fill(0);
    for (let [aft, pre] of prerequisites) {
        edges[pre].push(aft);
        indeg[pre]++;
    }
    const queue = [],
        res = [];
    for (let i = 0; i < numCourses; i++) if (indeg[i] === 0) queue.push(i);
    while (queue.length) {
        const node = queue.shift();
        res.push(node);
        for (let out of edges[node]) {
            --indeg[out];
            if (indeg[out] == 0) queue.push(out);
        }
    }
    if (res.length != numCourses) return [];
    return res;
};
